import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences

import pickle


def preprocess_text(text, tokenizer, max_sequence_length):
    # 将输入文本转换成数字序列
    sequence = tokenizer.texts_to_sequences([text])
    # 填充序列
    sequence_padded = pad_sequences(sequence, maxlen=max_sequence_length, padding='post', truncating='post')
    return sequence_padded


def predict_probability(input_text, model, tokenizer, max_sequence_length=3000):
    # 预处理输入文本
    input_sequence = preprocess_text(input_text, tokenizer, max_sequence_length)
    # 使用模型进行预测
    predictions = model.predict(input_sequence)
    # 获取标签为 '1' 的概率值
    probability_label_1 = predictions[0][0]
    return probability_label_1


# 假设已经保存好了模型文件 model_filename，和 tokenizer
model_filename = 'static/model_02/model_epoch_2.h5'
tokenizer_filename = 'static/model_02/tokenizer.pkl'

# 加载模型
model = load_model(model_filename)

# 加载 tokenizer
with open(tokenizer_filename, 'rb') as f:
    tokenizer = pickle.load(f)
